package com.gjy.rocketmq.product;

import com.gjy.rocketmq.RocketUtil;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 异步消息
 *
 * @author 宫静雨
 * @version 1.0
 * @since 2023-01-29 09:16:23
 */
public class ASyncProduct {

    private static final Logger logger = LoggerFactory.getLogger(ASyncProduct.class);

    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer(RocketUtil.ProducerGroup);
        producer.setNamesrvAddr(RocketUtil.NAME_SRV);
        producer.start();

        for (int i = 0; i < 10; i++) {
            Message message = new Message(RocketUtil.TOPIC_TEST, "TagA",
                    ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    logger.info("发送成功: {}", sendResult);
                }

                @Override
                public void onException(Throwable e) {
                    logger.error("发送失败: {}", e.getMessage());
                }
            });
        }
        TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
        producer.shutdown();
    }
}
